package cn.acewill.yxd.yunxundian.ui.sign;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.Console;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.MyLookEvaluationRecycleAdatper;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.viewReportBean;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.CacheActivity;

/**
 * Created by XXX on 2017/8/9.
 */

public class LookEvaDetialActivity extends BaseActivity{

    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private RecyclerView itemList;
    private ProgressBar myProgressBar;
    private ArrayList<viewReportBean> list=new ArrayList<>();
    private MyLookEvaluationRecycleAdatper adapter;
    private int schid;

  //  private RelativeLayout loaddingview;
    //是否是上级
    private boolean isManager=false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.look_evaluation_body);
        CacheActivity.addActivity(this);
        initbody();
        initRecycle();
      //  loadNetData();
        //setShowOrGone(1);
        initWebViewData();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (isManager==true){
            getMenuInflater().inflate(R.menu.menu_action_plan,menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    public void initWebViewData(){
        myProgressBar = (ProgressBar) findViewById(R.id.rvPbar);
        WebView webView = (WebView) findViewById(R.id.webView_loadData);
        String url = pubClass.Server_lookReport + "schid="+schid;
        webView.loadUrl(url);
        //setShowOrGone(3);
        webView.getSettings().setJavaScriptEnabled(true);// 支持运行javascript
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.setWebChromeClient(new WebChromeClient()
                                   {
                                       @Override
                                       public void onProgressChanged(WebView view, int newProgress) {
                                           if (newProgress == 100) {
                                               myProgressBar.setVisibility(View.INVISIBLE);
                                           } else {
                                               if (View.INVISIBLE == myProgressBar.getVisibility()) {
                                                   myProgressBar.setVisibility(View.VISIBLE);
                                               }
                                               myProgressBar.setProgress(newProgress);
                                           }
                                           super.onProgressChanged(view, newProgress);
                                       }
                                   }
        );// 支持运行特殊的javascript（例如：alert()）
        webView.setWebViewClient(new WebViewClient());// 当点击超链地址后不会新打开浏览器来访问，而是始终在本app中浏览页面
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (isManager==true){
            switch (item.getItemId()){
                case R.id.addplan:
                    startActivity(new Intent(this,WenTiFenXiListActivity.class).putExtra("schid",schid));
                    break;
            }
        }

        return super.onOptionsItemSelected(item);
    }

    private void initbody(){
        schid=getIntent().getIntExtra("schid",0);
        //是否是当前门店的管理者
        try {
            Schedule schedule = db.selector(Schedule.class).where("ID","=",schid).findFirst();
            if (schedule!=null){
                if (schedule.getStates()==3&&schedule.getIsNeedShopReport()==1){
                    if (schedule.getToUserId() == MainActivity.id || schedule.getShopmanId() == MainActivity.id) {
                        isManager = true;
                    }
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }

      //  loaddingview= (RelativeLayout) findViewById(R.id.loadingRel);
        this.itemList = (RecyclerView) findViewById(R.id.itemList);
        this.itemList.setVisibility(View.GONE);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
       // setShowOrGone(1);
    }

    public void initRecycle() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(OrientationHelper.VERTICAL);
        itemList.setLayoutManager(manager);
        itemList.setVisibility(View.GONE);
    }


    public void loadNetData() {
        Map<String, String> map = new HashMap<>();
        map.put("schid", schid+"");
        map.put("task", "viewReport");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                 //   setShowOrGone(2);
                    String[] array = result.split("\\|");
                    if (array[0].equals("200")) {
                        Gson gson = new Gson();
                        Type typeList = new TypeToken<ArrayList<viewReportBean>>() {
                        }.getType();
                        list = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                        adapter = new MyLookEvaluationRecycleAdatper(LookEvaDetialActivity.this,list);
                        itemList.setAdapter(adapter);
                    }
                    else {
                        BaseActivity.showAnimaDialog(LookEvaDetialActivity.this,array[1]);
                    }
                }
                @Override
                public void onFailture() {
                 //   setShowOrGone(3);
                    BaseActivity.showAnimaDialog(LookEvaDetialActivity.this,"数据请求失败，请检查网络状况");
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //接受网络状态的判断广播
    NetWorkStateReceiver netWorkStateReceiver;
    int whetherConnectNetWork=0;
    @Override
    protected void onResume() {
        if (netWorkStateReceiver==null){
            netWorkStateReceiver=new NetWorkStateReceiver();
        }
        IntentFilter filter=new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver,filter);
        System.out.print("广播注册");
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkStateReceiver);
        System.out.print("广播注销");
    }

    //用于离线状态下的voice的点击
    class NetWorkStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo!=null){
                whetherConnectNetWork=1;
                if(list!=null&&list.size()!=0){
                    //已经加载完成
                }else{
                    //离线还未加载出来
               //     setShowOrGone(1);
                //    loadNetData();
                }
            }else{
                whetherConnectNetWork=0;

            }
        }
    }
//    public void setShowOrGone(int k){
//        if (k==1){
//            loaddingview.setVisibility(View.VISIBLE);
//            itemList.setVisibility(View.GONE);
//        }
//        if (k==2){
//            loaddingview.setVisibility(View.GONE);
//            itemList.setVisibility(View.VISIBLE);
//        }
//        if (k==3){
//            loaddingview.setVisibility(View.GONE);
//        }
//    }

    @Override
    protected void onStop() {
        super.onStop();
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
    }

    @Override
    public void onBackPressed() {
        if (NiceVideoPlayerManager.instance().onBackPressd()) return;
        super.onBackPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
        }
        return super.onKeyDown(keyCode, event);
    }
}
